useCallback 使用方式參數都與useMemo類似,也一樣使用JS緩存
使用在控制組件更新
最大的不同,在於useCallback是函數可以直接以函數來執行
import React, {useState,useCallback} from 'react';
const Test1 = ({nums,conus}) => {
let umemo = useCallback(()=>{
return {nums,conus};
},[nums]);
return(
<div>Test1-num{umemo().nums}-conut{umemo().conus}</div>
);
}
export default function App() {
const [count, setCount] = useState(0);
const [num, setNum] = useState(0);
return (
<div>
<Test1 nums={num} conus={count} />
<p>count:{count}</p>
<p>num:{num}</p>
<button onClick={(e) => { setCount( count+1 );console.log("count"+count); }}>ADD-count</button>
<button onClick={(e) => { setNum( num+1 );console.log("num"+num); }}>ADD-num</button>
</div>
)
}
最大的差異就是可以直接只用usecallback()
比較一下
import React, {useState,useCallback,useMemo,} from 'react';
const Test1 = ({nums,conus}) => {
let usecallback = useCallback(()=>{
return {nums,conus};
},[nums]);
return(
<div>useCallback-num{usecallback().nums}-conut{usecallback().conus}</div>
);
}
const Test2 = ({nums,conus}) => {
let umemo = useMemo(()=>{
return {nums,conus};
},[nums]);
return(
<div>useMemo-num{umemo.nums}-conut{umemo.conus}</div>
);
}
export default function App() {
const [count, setCount] = useState(0);
const [num, setNum] = useState(0);
return (
<div>
<Test1 nums={num} conus={count} />
<Test2 nums={num} conus={count} />
<p>count:{count}</p>
<p>num:{num}</p>
<button onClick={(e) => { setCount( count+1 );console.log("count"+count); }}>ADD-count</button>
<button onClick={(e) => { setNum( num+1 );console.log("num"+num); }}>ADD-num</button>
</div>
)
}
useCallback能用函數操作數據上會比較方便,比如傳值打API就可以用到,非常的實用,useCallback第2個參數反而比較用不到,既然是函數就可以用JS的方式來判斷操作。